package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @Author: zt
 * @Date: 2021/4/30 14:05
 * @Description:
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    // 注入数据源
    @Autowired
    private DataSource dataSource;
    // 配置对象
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 配置没有权限访问跳转自定义页面
        http.exceptionHandling().accessDeniedPage("/unauth.html");
        // 配置退出
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();

        http
                .formLogin()
                .loginPage("/login.html") // 自定义 login 页面
                // /user/login 是随便写的，Security会自动处理
                .loginProcessingUrl("/user/login") // 处理登录的URL（controller）
                .defaultSuccessUrl("/success.html").permitAll() // 登录成功后跳转的页面
                .and().authorizeRequests() // 需要设置权限的请求
                .antMatchers("/", "/test/hello", "/user/login").permitAll() // 不需要过滤的资源
                .antMatchers("/test/auth").hasRole("sale")
                .anyRequest().authenticated() // 任何请求都可以访问
                .and().rememberMe().tokenRepository(persistentTokenRepository()) // 设置记住我的数据库对象
                .tokenValiditySeconds(60) // 记住我的过期时间，单位秒
                // 跨站伪造攻击：比如同一个网站打开了淘宝和钓鱼网站，那么钓鱼网站就能通过浏览器获取淘宝的cookie
                .and().csrf().disable();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 对登录密码进行加密处理
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
